﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
/*
	TODO:
	5. Show template in status bar. Click bar to edit/clear.
*/
namespace DbView
{
	public partial class ClipboardTemplateForm : Form
	{
		public ClipboardTemplateForm(String template)
		{
			InitializeComponent();
			Template = template;
		}


		public string Template { get; set; }

		private void btnOk_Click(object sender, EventArgs e)
		{
			if (ValidatedOK())
			{
				Template = this.txtTemplate.Text;
				this.DialogResult = System.Windows.Forms.DialogResult.OK;
				this.Close();
			}
		}

		private bool ValidatedOK()
		{
			string temp = this.txtTemplate.Text;
			if (temp.Length == 0) return true; // empty is valid
			string message = "";
			if (temp.IndexOf("{0}") == -1)
			{
				message = @"
The template should contain the placemarker {0} otherwise data will
not be copied into the clipboard
";
			}
			else
			{
				int[] tagNums = GetTags();
				// test for gaps in multiple tag entries.
				for (int i = 1; i < tagNums.GetLength(0); ++i)
				{
					if (tagNums[i] - tagNums[i - 1] > 1)
					{
						message = string.Format(@"Tag number {0} is missing", tagNums[i - 1] + 1);
						break;
					}
				}
			}
			if (message.Length == 0) return true;
			MessageBox.Show(message, "Template Format Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
			return false;
		}

		private void btnClear_Click(object sender, EventArgs e)
		{
			Template = "";
			this.DialogResult = System.Windows.Forms.DialogResult.OK;
			this.Close();
		}

		private void btnCancel_Click(object sender, EventArgs e)
		{
			this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
			this.Close();
		}

		private void ClipboardTemplateForm_Load(object sender, EventArgs e)
		{
			this.txtTemplate.Text = Template;
		}

		private void btnSetTag_Click(object sender, EventArgs e)
		{
			// figure out the next one to use
			int nextNum = 0;
			foreach (int i in GetTags())
				if (i >= nextNum) nextNum = i + 1;
			string tag = "{" + nextNum.ToString() + "}";
			int insertPoint = this.txtTemplate.SelectionStart;
			this.txtTemplate.Text = this.txtTemplate.Text.Insert(insertPoint, tag);
			this.txtTemplate.SelectionStart = insertPoint + tag.Length;
			this.txtTemplate.Focus();
		}

		private int[] GetTags()
		{
			// find all {0}, {1} etc.
			System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex(@"\{\s*(\d+)\s*\}");
			System.Text.RegularExpressions.MatchCollection mc = r.Matches(this.txtTemplate.Text);
			List<int> numbers = new List<int>();
			foreach (System.Text.RegularExpressions.Match m in mc)
			{
				numbers.Add(Convert.ToInt32(m.Groups[1].Value));
			}
			numbers.Sort(); // one function will test the gap
			return numbers.ToArray();
		}


	}
}
